package com.hjy.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;

public class EncoderStudy {
    public static void main(String[] args) {
        //模拟服务器
        //使用EmbeddedChannel 测试handler
        EmbeddedChannel channel = new EmbeddedChannel(
                //数据最大长度为1kb 长度标识前后各有1个字节的附加嘻嘻 长度标识为4个字节 int
                new LengthFieldBasedFrameDecoder(1024, 1, 4, 1, 0),
                new LoggingHandler(LogLevel.DEBUG)
        );

        //模拟客户端写入数据
        ByteBuf buf = ByteBufAllocator.DEFAULT.directBuffer();
        send(buf, "hello");
        channel.writeInbound(buf);
        send(buf, "world");
        channel.writeInbound(buf);
    }

    private static void send(ByteBuf buf, String msg) {
        //得到数据的长度
        int len = msg.length();
        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
        //将数据写入buf
        //写入长度标识前其他的信息
        buf.writeByte(0xCA);
        buf.writeInt(len);//写入长度标识
        buf.writeByte(0xFE);//写入长度标识后其他的信息
        buf.writeBytes(bytes);//写入具体的数据

    }
}
